package com.xlf.service.base.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xlf.common.core.exception.BizException;
import com.xlf.common.core.util.BeanCopyUtils;
import com.xlf.common.core.util.StringUtils;
import com.xlf.pojo.base.Difficulty;
import com.xlf.pojo.base.Problem;
import com.xlf.service.base.mapper.ProblemMapper;
import com.xlf.service.base.service.DifficultyService;
import com.xlf.service.base.mapper.DifficultyMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
* @author 小新
* @description 针对表【difficulty】的数据库操作Service实现
* @createDate 2023-10-03 10:12:07
*/
@Service
public class DifficultyServiceImpl extends ServiceImpl<DifficultyMapper, Difficulty>
    implements DifficultyService{

    @Resource
    ProblemMapper problemMapper;

    @Override
    public List<Difficulty> getList(Difficulty difficulty) {
        LambdaQueryWrapper<Difficulty> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(difficulty.getName()),Difficulty::getName,difficulty.getName());
        List<Difficulty> list = list(wrapper);
        if(StringUtils.isNotEmpty(list)){
            list.forEach(item -> {
                Long aLong = problemMapper.selectCount(new LambdaQueryWrapper<Problem>()
                        .eq(Problem::getDifficultyId,item.getId()));
                item.setProblemNum(Math.toIntExact(aLong));
            });
        }
        return list;
    }

    /**
     *
     * @param ids
     * @return
     */
    @Transactional
    @Override
    public void delete(List<String> ids) {

        Assert.notNull(ids,() -> new BizException("列表不能为空"));
        ids.forEach(item -> {
            Long count = problemMapper.selectCount(new LambdaQueryWrapper<Problem>().eq(Problem::getDifficultyId, item));
            if(count > 0){
                throw new BizException("该分类下存在题目，不允许删除！");
            }
            removeById(item);
        });
        return;
    }

    @Override
    public boolean updateStatus(Difficulty difficulty) {
        return lambdaUpdate().set(Difficulty::getStatus,difficulty.getStatus()).eq(Difficulty::getId,difficulty.getId()).update();
    }
}




